<template>
  <LoginDialog ref="loginDialogRef" />
  
  <div class="qa-wrapper">
    <el-carousel height="150px">
      <el-carousel-item v-for="item in 4" :key="item">
        <!-- <h3 class="small">{{ item }}</h3> -->
      </el-carousel-item>
    </el-carousel>
    <!-- 登录弹窗 -->
    <div class="wrapper-header">
      <div class="switch">
       
      </div>
      <!-- <div class="search">
        <van-button size="small" icon="replay">刷新</van-button>
      </div> -->
    </div>
    <div class="wrapper-list">
      <div class="card-container">
        <div v-for="(product, index) in productList" :key="product.id" class="card-item">
          <div class="card">
            <div class="card-content">
              <img
                class="card-thumb"
                :src="'https://img1.baidu.com/it/u=2507594473,1871592933&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1311'"
                alt="产品图片"
              />

              <div class="card-text">
                <h2 class="card-title">{{ product.name }}</h2>
                <p class="card-desc">{{ product.description }}</p>
                <div class="card-line"></div>
                <p class="card-info">月息：{{ product.interestDesc }}</p>
                <div class="card-line"></div>
                <p class="card-info">期数：{{ product.termDesc }}</p>
                <div class="card-line"></div>
                <p class="card-info card-amount">额度：{{ product.limitAmount }}</p>
                <div class="card-line"></div>
                <p class="card-info card-desc">利息划算，办理便捷，还款灵活，最快当天放款</p>
              </div>
            </div>
            <div class="card-footer">
              <button class="apply-button" @click="openDialog(product)">了解可申请额度</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 申请弹窗 -->
    <el-dialog v-model="dialogVisible" :title="`申请 （${ selectedProduct.limitAmount || '' }）`" width="600px" class="custom-dialog">
      <el-form ref="formRef" label-position="right":model="form" :rules="rules" style="margin-top: 5px" scrollable>
        <el-form-item label="周期" prop="weekNum" label-width="100px">
          <el-select v-model="form.weekNum" placeholder="请选择周期">
            <el-option label="12周" value="12"></el-option>
            <el-option label="8周" value="8"></el-option>
            <el-option label="4周" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓  名" prop="name" label-width="100px">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="身份证" prop="idCard" label-width="100px">
          <el-input v-model="form.idCard" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="100px">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="微信号" prop="wechat" label-width="100px">
          <el-input v-model="form.wechat" />
        </el-form-item>
        <el-form-item label="公司" prop="org" label-width="100px">
          <el-input v-model="form.org" />
        </el-form-item>
        <el-form-item label="公司地址" prop="orgAddress" label-width="100px">
          <el-input v-model="form.orgAddress" />
        </el-form-item>
        <el-form-item label="公司电话" prop="orgTel" label-width="100px">
          <el-input v-model="form.orgTel" />
        </el-form-item>
        <el-form-item label="紧急联系人(1)" prop="contact1" label-width="130px">
          <el-input v-model="form.contact1" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel1" label-width="130px">
          <el-input v-model="form.contactTel1" />
        </el-form-item>
        <el-form-item label="紧急联系人(2)" prop="contact2" label-width="130px">
          <el-input v-model="form.contact2" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel2" label-width="130px">
          <el-input v-model="form.contactTel2" />
        </el-form-item>
        <el-form-item label="支付宝芝麻分截图" prop="zfbUrl" label-width="150px">
          <el-upload class="upload-block" action="#" :before-upload="beforeUpload" :show-file-list="false">
            <el-button type="primary">上传支付宝芝麻分截图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="公积金首页明细截图" prop="gjjUrl" label-width="150px">
          <el-upload class="upload-block" action="#" :before-upload="beforeUpload" :show-file-list="false">
            <el-button type="primary">上传公积金首页明细截图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证正面" prop="idFrontUrl" label-width="130px">
          <el-upload class="upload-block" action="#" :before-upload="beforeUpload" :show-file-list="false">
            <el-button type="primary">上传身份证正面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证反面" prop="idBackUrl" label-width="130px">
          <el-upload class="upload-block" action="#" :before-upload="beforeUpload" :show-file-list="false">
            <el-button type="primary">上传身份证反面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="手持身份证图片" prop="idPhotoUrl" label-width="130px">
          <el-upload class="upload-block" action="#" :before-upload="beforeUpload" :show-file-list="false">
            <el-button type="primary">上传手持身份证图片</el-button>
          </el-upload>
        </el-form-item>
       
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as httpService from '@/services/apply.service'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/useStore'
import LoginDialog from '@/view/user/LoginDialog.vue'

const userStore = useUserStore()
const productList = ref([])
const dialogVisible = ref(false)
const selectedProduct = ref({}) // 防止undefined
const formRef = ref(null)
const form = ref({
  name: '',
  idCard: '',
  phone: '',
  wechat: '',
  org: '',
  orgAddress: '',
  orgTel: '',
  contact1: '',
  contactTel1: '',
  contact2: '',
  contactTel2: '',
  zfbUrl: null,
  gjjUrl: null,
  idFrontUrl: null,
  idBackUrl: null,
  idPhotoUrl: null,
  weekNum: null
})
const loginDialogRef = ref(null)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  wechat: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
  org: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  orgAddress: [{ required: true, message: '请输入公司地址', trigger: 'blur' }],
  orgTel: [{ required: true, message: '请输入公司电话', trigger: 'blur' }],
  contact1: [{ required: true, message: '请输入紧急联系人1姓名', trigger: 'blur' }],
  contactTel1: [{ required: true, message: '请输入紧急联系人1电话', trigger: 'blur' }],
  contact2: [{ required: true, message: '请输入紧急联系人2姓名', trigger: 'blur' }],
  contactTel2: [{ required: true, message: '请输入紧急联系人2电话', trigger: 'blur' }],
  zfbUrl: [{ required: true, message: '请上传支付宝芝麻分截图', trigger: 'change' }],
  gjjUrl: [{ required: true, message: '请上传公积金首页明细截图', trigger: 'change' }],
  idFrontUrl: [{ required: true, message: '请上传身份证正面', trigger: 'change' }],
  idBackUrl: [{ required: true, message: '请上传身份证反面', trigger: 'change' }],
  idPhotoUrl: [{ required: true, message: '请上传手持身份证图片', trigger: 'change' }],
  weekNum: [{ required: true, message: '请选择还款周期', trigger: 'change' }]
}

// 获取产品列表
const fetchProductList = async () => {
  try {
    const response = await httpService.getProductList()
    productList.value = response.data || []
  } catch (error) {
    ElMessage.error('获取产品列表失败！')
  }
}

// 打开弹窗
const openDialog = (product) => {
  // 检查是否已登录
  if (!userStore.authInfo) {
    loginDialogRef.value?.openDialog() // 使用 `?.` 避免 `null` 报错
    return
  }
  selectedProduct.value = { ...product } // 确保数据正确
  dialogVisible.value = true
}

// **提交表单**
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }
    try {
      const applyData = {
        ...form.value,
        productId: selectedProduct.value.id, // 关联产品
      }
      if (form.value.id) {
        await httpService.updateApplyRecord(applyData) // 修改记录
        ElMessage.success('更新成功！')
      } else {
        await httpService.addApplyRecord(applyData) // 新增记录
        ElMessage.success('提交成功！')
      }
      dialogVisible.value = false
    } catch (error) {
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}

// 上传前检查
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  return true
}

onMounted(() => {
  fetchProductList()
})
</script>

<style scoped>
.qa-wrapper {
  padding: 20px;
}
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

/* 头部样式 */
.header-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

/* 卡片容器样式 */
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  justify-content: space-between;
}

/* 单个卡片样式 */
.card-item {
  width: 48%;
}

.card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 10px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: 0px 6px 15px rgba(0, 0, 0, 0.15); /* 鼠标悬停时阴影加深 */
}

/* 卡片内容布局 */
.card-content {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.card-thumb {
  width: 40%;
  height: auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-right: 10px;
}

.card-text {
  flex: 1;
}

/* 卡片标题样式 */
.card-title {
  font-size: 20px;
  font-weight: bold;
  color: #187bf3;
  margin-bottom: 8px;
}

/* 描述文本 */
.card-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

/* 信息字段 */
.card-info {
  font-size: 14px;
  color: #666;
  margin: 5px 0;
}

.card-amount {
  font-size: 21px;
  font-weight: bold;
  color: rgb(238, 130, 71); /* 金额字体颜色 */
  font-weight: bold;
}
.card-desc {
  font-size: 21px;
  font-weight: bold;
  color: rgb(11, 4, 0); /* 金额字体颜色 */
  font-weight: bold;
}

/* 间隔线 */
.card-line {
  height: 1px;
  background-color: #f2f2f2;
  margin: 8px 0;
}
.wrapper-header {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  .switch {
    display: flex;
    align-items: center;
    .text {
      font-size: 14px;
      color: #666;
      margin-left: 10px;
    }
  }
  .search {
    .van-button {
      margin-left: 10px;
    }
  }
}

/* 卡片底部样式 */
.card-footer {
  text-align: right;
  margin-top: 10px;
}

.apply-button {
  padding: 6px 12px;
  font-size: 14px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.apply-button:hover {
  background-color: #3079ed;
}

/* 表单样式 */
.custom-dialog {
  max-height: 90vh;
}
</style>
